package br.com.findme.findmeserver.controle;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import br.com.findme.findmeserver.dao.HibernateUtils;
import br.com.findme.findmeserver.entidade.Usuario;
import br.com.findme.findmeserver.mensagem.Mensagem;
import br.com.findme.findmeserver.utils.SenhaUtils;

import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class LoginServlet
 */

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Mensagem m = null;
		
		try {
			String login = request.getParameter("email");
			String senha = request.getParameter("senha");
			
			senha = SenhaUtils.encodeMD5(senha);
			
			Session session = HibernateUtils.openSession();
			
			Criteria c =  session.createCriteria(Usuario.class);			
			c.add(Restrictions.and(Restrictions.eq("email", login), Restrictions.eq("senha", senha)));
		
			Usuario usuario = (Usuario) c.uniqueResult();
			
			if(usuario != null){				
				m = new Mensagem(Mensagem.STATUS_VERDADEIRO, usuario);
			}else{
				m = new Mensagem(Mensagem.STATUS_FALSO, "Usuário e/ou senha inválido(s).");			
			}
		
		} catch (Exception e) {
			
			m = new Mensagem(Mensagem.STATUS_ERRO, "Não foi possível realizar o login por favor tente mais tarde.");			
		}
		
		PrintWriter pw = response.getWriter();		
		GsonBuilder gb = new GsonBuilder();
		gb.registerTypeAdapter(Usuario.class, Usuario.toJSON());	
		pw.write(m.toString(gb.create()));
	}

}
